package com.smile.ye.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smile.ye.data.dto.AuthLoginDto;
import com.smile.ye.data.dto.AuthRegisterDto;
import com.smile.ye.data.entity.ProductItemEntity;
import com.smile.ye.data.entity.UserEntity;
import com.smile.ye.data.vo.StoreVo;
import com.smile.ye.mapper.StoreMapper;
import com.smile.ye.mapper.UserMapper;
import com.smile.ye.response.Result;
import com.smile.ye.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Component
public class AuthService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    StoreMapper mapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    JavaMailSender sender;
    @Value("${spring.mail.username}")
    private String form;
    public Result login(AuthLoginDto dto){
        String password = dto.getPassword();
        String username = dto.getUsername();
        if(StringUtils.isBlank(password) || StringUtils.isBlank(username)) throw new RuntimeException("账号或密码不能为空!");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password,null);
        authenticationManager.authenticate(authenticationToken);
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UserEntity::getUsername,username);
        UserEntity user = userMapper.selectOne(wrapper);
        String token = JwtUtils.createToken(username,user.getId());
        HashMap<String,Object> map = new HashMap();
        map.put("token",token);
        redisTemplate.opsForValue().set(dto.getUsername() + "Authorization",token,  60 * 60 *24 , TimeUnit.SECONDS);
        return Result.build(map);
    }

    public Result code(String email){
        try{
            System.out.println(email);
            if(email.isEmpty()) throw new RuntimeException("邮箱不能为空!");
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            Random random = new Random();
            int code = random.nextInt(899999) + 100000;
            redisTemplate.opsForValue().set("email"+email,code);
            mailMessage.setSubject("注册码");
            mailMessage.setText(""+code);
            mailMessage.setTo(email);
            mailMessage.setFrom(form);
            sender.send(mailMessage);
            return Result.build();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    public Result register(AuthRegisterDto dto){
        String code = dto.getCode();
        UserEntity user = new UserEntity();
        user.setEmail(dto.getEmail());
        user.setPassword(dto.getPassword());
        user.setUsername(dto.getUsername());
        if(StringUtils.isBlank(code)) throw new RuntimeException("验证码不能为空!");
        if(StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getEmail())) throw new RuntimeException("账号或密码不可为空!");
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getUsername, user.getUsername());
        UserEntity users = userMapper.selectOne(wrapper);
        if(users!=null) throw new RuntimeException("账号已存在");
        String email = user.getEmail();
        Object res = redisTemplate.opsForValue().get("email"+email).toString();
        if(res==null || !res.equals(code)) throw new RuntimeException("验证码错误!");
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        int i = userMapper.insert(user);
        if(i>0) {
            redisTemplate.delete("email"+email);
            return Result.build("OK");
        }
        throw new RuntimeException("注册失败，请重新注册");
    }
//    public Result forget(){
//
//    }
    public Result queryStore(){
        List<StoreVo> storeVos = mapper.queryStore("18783116545");
        return Result.build(storeVos);
    }
}
